// useDataFetching.ts
import { ref } from 'vue';

// 去重函数
const uniqueArray = (arr: any[], field: string) => {
  const map = new Map();
  return arr.filter((item) => {
    const key = item[field];
    if (!map.has(key)) {
      map.set(key, true);
      return true;
    }
    return false;
  });
};

// 获取全量数据的函数
const getAllData = async (api: Function, params: any, field: string) => {
  let allData = [];
  let pageNo = 1;
  let hasMore = true;

  while (hasMore) {
    const newParams = { ...params, pageNo };
    const res = await api(newParams);
    if (res.list && res.list.length > 0) {
      allData = allData.concat(res.list);
      pageNo++;
    } else {
      hasMore = false;
    }
  }

  return uniqueArray(allData, field);
};

// 封装成组合式函数
export const useDataFetching = () => {
  return {
    uniqueArray,
    getAllData,
  };
};